package com.plian.system.service.qg.guarantee.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.plian.Tools.*;
import com.plian.Tools.pagedata.PageData;
import com.plian.system.cache.UserCache;
import com.plian.system.common.status.CheckStatus;
import com.plian.system.constant.baseinfo.ValueSetConstant;
import com.plian.system.constant.sys.FormStatusConstant;
import com.plian.system.constant.sys.FormTypeConstant;
import com.plian.system.constant.yth.YthConstant;
import com.plian.system.dao.sys.orgzation.OrgzationDao;
import com.plian.system.dto.qg.guarantee.PropertyGuaranteeApplyDTO;
import com.plian.system.entity.qg.guarantee.PropertyGuaranteeApply;
import com.plian.system.entity.qg.guarantee.PropertyGuaranteeAudit;
import com.plian.system.entity.qg.guarantee.PropertyGuaranteeExecute;
import com.plian.system.entity.qg.guarantee.PropertyGuaranteeWarrantee;
import com.plian.system.entity.sys.ApprovalMessage;
import com.plian.system.mapper.qg.guarantee.PropertyGuaranteeApplyMapper;
import com.plian.system.mapper.qg.guarantee.PropertyGuaranteeExecuteMapper;
import com.plian.system.mybatis.base.BaseFlowService;
import com.plian.system.mybatis.base.BaseServiceImpl;
import com.plian.system.mybatis.support.Condition;
import com.plian.system.service.bt.baseinfo.BaseInfoService;
import com.plian.system.service.qg.guarantee.IPropertyGuaranteeApplyService;
import com.plian.system.service.qg.guarantee.IPropertyGuaranteeAuditService;
import com.plian.system.service.qg.guarantee.IPropertyGuaranteeWarranteeService;
import com.plian.system.service.sys.code.IFormCodeService;
import com.plian.system.service.sys.message.IApprovalMessageService;
import com.plian.system.service.sys.orgzation.IOrgService;
import com.plian.system.service.sys.orgzation.OrgzationService;
import com.plian.system.service.wf.FormWorkflowService;
import com.plian.system.vo.qg.guarantee.GuaranteeUnitSummaryVO;
import com.plian.system.vo.qg.guarantee.PropertyGuaranteeApplyVO;
import com.plian.system.vo.report.HeaderVO;
import com.plian.system.vo.report.ReportReturnVO;
import com.plian.system.vo.report.ReportVO;
import com.plian.system.vo.yth.YthResult;
import com.plian.system.wrapper.qg.guarantee.PropertyGuaranteeApplyWrapper;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import static com.plian.system.constant.sys.ApprovalMessageTypeConstant.GZW_TYPE;
import static com.plian.system.constant.sys.FormStatusConstant.UNREVIEWED;

/**
 * 企业担保申请主表 服务实现类
 *
 * @author jianglei
 * @since 2019-10-23
 */
@Slf4j
@Service
@AllArgsConstructor
public class PropertyGuaranteeApplyServiceImpl extends BaseServiceImpl<PropertyGuaranteeApplyMapper, PropertyGuaranteeApply> implements IPropertyGuaranteeApplyService, BaseFlowService {


	private IPropertyGuaranteeAuditService propertyGuaranteeAuditService;

	private IPropertyGuaranteeWarranteeService propertyGuaranteeWarranteeService;

	private PropertyGuaranteeApplyMapper propertyGuaranteeApplyMapper;

	private PropertyGuaranteeExecuteMapper propertyGuaranteeExecuteMapper;

	private FormWorkflowService formWorkflowService;

	private OrgzationService orgzationService;

	private OrgzationDao orgzationDao;

	private IFormCodeService formCodeService;

	private BaseInfoService baseInfoService;

	private PropertyGuaranteeApplyWrapper propertyGuaranteeApplyWrapper;

	private IOrgService orgService;

	private IApprovalMessageService approvalMessageService;

	@Override
	public boolean saveOrUpdate(PropertyGuaranteeApply propertyGuaranteeApply) {
		if (!Optional.ofNullable(propertyGuaranteeApply.getId()).isPresent()) {
			propertyGuaranteeApply.setVersion("1");
		}
		if (!Optional.ofNullable(propertyGuaranteeApply.getGuaranteeTotal()).isPresent()){
			propertyGuaranteeApply.setGuaranteeTotal(new BigDecimal(0));
		}
		//保存时一定执行剩余可担保金额=担保额-累计担保额
		propertyGuaranteeApply.setGuaranteeRemain(propertyGuaranteeApply.getGuaranteeAmount().subtract(propertyGuaranteeApply.getGuaranteeTotal()));

		if (propertyGuaranteeApply.getId() == null){
			propertyGuaranteeApply.setCode(formCodeService.getCode(FormTypeConstant.QG_GUARANTEE_APPLY_FORM));
			propertyGuaranteeApply.setFormType(String.valueOf(FormTypeConstant.QG_GUARANTEE_APPLY_FORM));
		}
		if (!Optional.ofNullable(propertyGuaranteeApply.getStatus()).isPresent()) {
			propertyGuaranteeApply.setStatus(FormStatusConstant.UNREVIEWED);
		}
		return super.saveOrUpdate(propertyGuaranteeApply);
	}

	@Override
	@Transactional(rollbackFor=RuntimeException.class)
	public boolean deleteLogic(List<Long> ids) {
		for (Long id : ids) {
			PropertyGuaranteeApply propertyGuaranteeApply = getById(id);
			if (propertyGuaranteeApply == null) {
				return false;
			} else if (propertyGuaranteeApply.getStatus() != null &&
					(propertyGuaranteeApply.getStatus() != FormStatusConstant.STASH && propertyGuaranteeApply.getStatus() != FormStatusConstant.UNREVIEWED)) {
				return false;
			}
			formWorkflowService.deleteProcessInstance(String.valueOf(id));
		}
		boolean result = super.deleteLogic(ids);
		propertyGuaranteeAuditService.deleteLogicByPropertyGuaranteeApplyId(ids);
		propertyGuaranteeWarranteeService.deleteLogicByPropertyGuaranteeApplyId(ids);
		return result;
	}

	@Override
	public HashMap<String,Object> commit(String id) {
		handleStatus(Long.valueOf(id), FormStatusConstant.FLOW,null);

		//将需要提交的流程变量返回，用于工作流侧
		return new HashMap<String,Object>();
	}

	@Override
	public Boolean finish(String id) {
		return handleStatus(Long.valueOf(id), FormStatusConstant.FINISH,"审批通过");
	}

	@Override
	public Boolean reject(String id, int formState, String comment) {
		return handleStatus(Long.valueOf(id), formState,null);
	}


	@Override
	public Boolean checkIsExisted(Long id, String code) {
		if (Optional.ofNullable(code).isPresent()) {
			PropertyGuaranteeApply propertyGuaranteeApply = new PropertyGuaranteeApply();
			propertyGuaranteeApply.setCode(code);
			if (Optional.ofNullable(getOne(Condition.getQueryWrapper(propertyGuaranteeApply))).isPresent()) {
				if (id == null || !id.equals(getOne(Condition.getQueryWrapper(propertyGuaranteeApply)).getId())) {
					return false;
				}
			}
		}

		return true;
	}

	@Override
	@Transactional(rollbackFor=RuntimeException.class)
	public Boolean submit(PropertyGuaranteeApply propertyGuaranteeApply) {

		if (!Optional.ofNullable(propertyGuaranteeApply.getStatus()).isPresent()){
			propertyGuaranteeApply.setStatus(FormStatusConstant.UNREVIEWED);
		}

		boolean result = saveOrUpdate(propertyGuaranteeApply);
		List<PropertyGuaranteeAudit> propertyGuaranteeAudits = propertyGuaranteeApply.getPropertyGuaranteeAudits();
		if (CollectionUtil.isNotEmpty(propertyGuaranteeAudits)) {
			/**
			 * 评估师信息
			 */
			List<Long> delIds = propertyGuaranteeAudits.stream().filter(propertyGuaranteeAudit ->
				Optional.ofNullable(propertyGuaranteeAudit.getIsDeleted()).isPresent() && propertyGuaranteeAudit.getIsDeleted() == 1)
				.map(PropertyGuaranteeAudit::getId).collect(Collectors.toList());
			if (CollectionUtil.isNotEmpty(delIds)) {
				propertyGuaranteeAuditService.deleteLogic(delIds);
			}

			propertyGuaranteeAudits.removeIf(propertyGuaranteeAudit -> (Optional.ofNullable(propertyGuaranteeAudit.getIsDeleted()).isPresent()
				&& propertyGuaranteeAudit.getIsDeleted() == 1));


			if (CollectionUtil.isNotEmpty(propertyGuaranteeAudits)) {
				/**
				 * 给新增数据赋值
				 */
				propertyGuaranteeAudits.stream().filter(propertyGuaranteeAudit -> propertyGuaranteeAudit.getId() == null)
					.forEach(propertyGuaranteeAudit -> {
						propertyGuaranteeAudit.setPropertyGuaranteeApplyId(propertyGuaranteeApply.getId());
						propertyGuaranteeAudit.setStatus(FormStatusConstant.UNREVIEWED);
						propertyGuaranteeAudit.setIsDeleted(0);
					});
				propertyGuaranteeAuditService.saveOrUpdateBatch(propertyGuaranteeAudits);
			}
		}

		List<PropertyGuaranteeWarrantee> propertyGuaranteeWarrantees = propertyGuaranteeApply.getPropertyGuaranteeWarrantees();
		if (CollectionUtil.isNotEmpty(propertyGuaranteeWarrantees)) {
			/**
			 * 被担保人上年末经审计
			 */
			List<Long> delIds = propertyGuaranteeWarrantees.stream().filter(propertyGuaranteeWarrantee ->
				Optional.ofNullable(propertyGuaranteeWarrantee.getIsDeleted()).isPresent() && propertyGuaranteeWarrantee.getIsDeleted() == 1)
				.map(PropertyGuaranteeWarrantee::getId).collect(Collectors.toList());
			if (CollectionUtil.isNotEmpty(delIds)) {
				propertyGuaranteeWarranteeService.deleteLogic(delIds);
			}

			propertyGuaranteeWarrantees.removeIf(propertyGuaranteeWarrantee ->
				(Optional.ofNullable(propertyGuaranteeWarrantee.getIsDeleted()).isPresent() && propertyGuaranteeWarrantee.getIsDeleted() == 1));


			if (CollectionUtil.isNotEmpty(propertyGuaranteeWarrantees)) {
				/**
				 * 给新增数据赋值
				 */
				propertyGuaranteeWarrantees.stream().filter(evaluationValue -> evaluationValue.getId() == null)
					.forEach(propertyGuaranteeWarrantee -> {
						propertyGuaranteeWarrantee.setPropertyGuaranteeApplyId(propertyGuaranteeApply.getId());
						propertyGuaranteeWarrantee.setStatus(FormStatusConstant.UNREVIEWED);
						propertyGuaranteeWarrantee.setIsDeleted(0);
					});
				propertyGuaranteeWarranteeService.saveOrUpdateBatch(propertyGuaranteeWarrantees);
			}
		}

		return result;
	}

	@Override
	public ReportReturnVO guaranteeUnitSummary(PropertyGuaranteeApplyDTO propertyGuaranteeApplyDTO) throws Exception{
		List<GuaranteeUnitSummaryVO> guaranteeUnitSummaryVOS = propertyGuaranteeApplyMapper.guaranteeUnitSummaryList(propertyGuaranteeApplyDTO);
		List<GuaranteeUnitSummaryVO> data = count(guaranteeUnitSummaryVOS, 1);

		ReportReturnVO reportReturnVO = new ReportReturnVO();
		ReportVO reportVO = new ReportVO();

		reportVO
			.addHeader(HeaderVO.builder().key("applyName").title("集团企业").build())
			.addHeader(HeaderVO.builder().key("year").title("年度").build())
			.addHeader(HeaderVO.builder().key("amount").title("申请单位累计申请金额（万元）").build())
			.addHeader(HeaderVO.builder().key("presentAmount").title("申请单位目前有效申请金额（万元）").build())
			.addHeader(HeaderVO.builder().key("yearAmount").title("申请单位当年累计申请金额（万元）").build());
		reportVO.setData(data);
		reportReturnVO.setGrids(reportVO);
		return reportReturnVO;
	}

	@Override
	public ReportReturnVO guaranteeSummary(PropertyGuaranteeApplyDTO propertyGuaranteeApplyDTO) throws Exception{
		List<GuaranteeUnitSummaryVO> guaranteeUnitSummaryVOS = propertyGuaranteeApplyMapper.guaranteeSummaryList(propertyGuaranteeApplyDTO);
		List<GuaranteeUnitSummaryVO> data = count(guaranteeUnitSummaryVOS, 1);

		ReportReturnVO reportReturnVO = new ReportReturnVO();
		ReportVO reportVO = new ReportVO();

		reportVO
			.addHeader(HeaderVO.builder().key("applyName").title("担保人").build())
			.addHeader(HeaderVO.builder().key("year").title("年度").build())
			.addHeader(HeaderVO.builder().key("amount").title("担保人累计担保额（万元）").build())
			.addHeader(HeaderVO.builder().key("presentAmount").title("担保人有效担保额（万元）").build())
			.addHeader(HeaderVO.builder().key("yearAmount").title("担保人当年累计担保额（万元）").build());
		reportVO.setData(data);
		reportReturnVO.setGrids(reportVO);
		return reportReturnVO;
	}

	@Override
	public ReportReturnVO warranteeSummary(PropertyGuaranteeApplyDTO propertyGuaranteeApplyDTO) throws Exception{
		List<GuaranteeUnitSummaryVO> guaranteeUnitSummaryVOS = propertyGuaranteeApplyMapper.warranteeSummaryList(propertyGuaranteeApplyDTO);
		List<GuaranteeUnitSummaryVO> data = count(guaranteeUnitSummaryVOS, 2);

		ReportReturnVO reportReturnVO = new ReportReturnVO();
		ReportVO reportVO = new ReportVO();

		reportVO
			.addHeader(HeaderVO.builder().key("applyName").title("被担保人").build())
			.addHeader(HeaderVO.builder().key("year").title("年度").build())
			.addHeader(HeaderVO.builder().key("amount").title("被担保人累计担保额（万元）").build())
			.addHeader(HeaderVO.builder().key("presentAmount").title("被担保人有效担保额（万元）").build())
			.addHeader(HeaderVO.builder().key("yearAmount").title("被担保人当年累计担保额（万元）").build());
		reportVO.setData(data);
		reportReturnVO.setGrids(reportVO);
		return reportReturnVO;
	}

	@Override
	public ReportReturnVO guaranteeAnnualAnalysis(PropertyGuaranteeApplyDTO propertyGuaranteeApplyDTO) {

		List<PropertyGuaranteeApply> propertyGuaranteeApplies = propertyGuaranteeApplyMapper.guaranteeAnnualAnalysisList(propertyGuaranteeApplyDTO);
		List<PropertyGuaranteeApplyVO> propertyGuaranteeApplyVOS = propertyGuaranteeApplyWrapper.entityToVO(propertyGuaranteeApplies);

		ReportReturnVO reportReturnVO = new ReportReturnVO();
		reportReturnVO.setCharts(JSONArray.parseArray(JSON.toJSONStringWithDateFormat(propertyGuaranteeApplyVOS, DateUtil.PATTERN_DATE , SerializerFeature.WriteDateUseDateFormat)));
		return reportReturnVO;
	}

	@Override
	public String checkExecute(Long id, PropertyGuaranteeExecute old, PropertyGuaranteeExecute now) {
		PropertyGuaranteeApply propertyGuaranteeApply = getById(id);
		if (old != null) {
			//剩余担保金额+旧数据 ，累计借款额-旧数据
			propertyGuaranteeApply.setGuaranteeRemain(propertyGuaranteeApply.getGuaranteeRemain().add(old.getUseAmount()));
			propertyGuaranteeApply.setTotalLoanAmount(propertyGuaranteeApply.getTotalLoanAmount() == null ?
				new BigDecimal(0).subtract(old.getLoanAmount()) : propertyGuaranteeApply.getTotalLoanAmount().subtract(old.getLoanAmount()));
		}
		if (now != null) {
			//剩余担保金额-新数据 ，累计借款额+新数据
			propertyGuaranteeApply.setGuaranteeRemain(propertyGuaranteeApply.getGuaranteeRemain().subtract(now.getUseAmount()));
			propertyGuaranteeApply.setTotalLoanAmount(propertyGuaranteeApply.getTotalLoanAmount() == null ?
				new BigDecimal(0).add(now.getLoanAmount()) : propertyGuaranteeApply.getTotalLoanAmount().add(now.getLoanAmount()));
		}
		if (propertyGuaranteeApply.getGuaranteeRemain().compareTo(new BigDecimal(0)) == -1) {
			return "超出剩余可担保金额";
		} else {
			propertyGuaranteeApply.setGuaranteeTotal(propertyGuaranteeApply.getGuaranteeAmount().subtract(propertyGuaranteeApply.getGuaranteeRemain()));
			saveOrUpdate(propertyGuaranteeApply);
		}

		return null;
	}

	@Override
	public Boolean checkCancel(Long id) {
		PropertyGuaranteeApply propertyGuaranteeApply = getById(id);
		if (!Optional.ofNullable(propertyGuaranteeApply).isPresent()) {
			return false;
		}
		QueryWrapper<PropertyGuaranteeExecute> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("upstream_code", propertyGuaranteeApply.getCode());
		if (CollectionUtil.isNotEmpty(propertyGuaranteeExecuteMapper.selectList(queryWrapper))) {
			return false;
		}
		return true;
	}

	/**
	 * type = 2 为被担保人汇总表 特殊处理
	 *
	 * @param guaranteeUnitSummaryVOS
	 * @param type
	 * @return
	 */
	private List<GuaranteeUnitSummaryVO> count(List<GuaranteeUnitSummaryVO> guaranteeUnitSummaryVOS, int type) throws Exception{
		if (CollectionUtil.isNotEmpty(guaranteeUnitSummaryVOS)) {
			if (type == 1){
				//所有单位
				List<PageData> allOrgs = orgzationDao.list(null);
				Map<String, String> map = new HashMap<>();
				if (CollectionUtil.isNotEmpty(allOrgs)){
					for (PageData org : allOrgs) {
						map.put((String)org.get("id"), (String)org.get("name"));
					}
				}
				guaranteeUnitSummaryVOS.forEach(guaranteeUnitSummaryVO -> {
					if(map.containsKey(guaranteeUnitSummaryVO.getApplyNameId())) {
						guaranteeUnitSummaryVO.setApplyName(map.get(guaranteeUnitSummaryVO.getApplyNameId()));
					}
				});
			}

			// 合计
			GuaranteeUnitSummaryVO end = new GuaranteeUnitSummaryVO();
			end.setApplyName("总计：" + guaranteeUnitSummaryVOS.size());
			for (GuaranteeUnitSummaryVO vo : guaranteeUnitSummaryVOS){
				end.setAmount(BigDecimalUtil.add(end.getAmount(), vo.getAmount()));
				end.setPresentAmount(BigDecimalUtil.add(end.getPresentAmount(), vo.getPresentAmount()));
				end.setYearAmount(BigDecimalUtil.add(end.getYearAmount(), vo.getYearAmount()));
			}
			guaranteeUnitSummaryVOS.add(end);
		}
		return guaranteeUnitSummaryVOS;
	}

	@Override
	public List<PageData> findByIds(List<String> formIds) {
		LambdaQueryWrapper<PropertyGuaranteeApply> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.in(PropertyGuaranteeApply::getId, Func.toLongList(StringUtils.join(formIds, StringPool.COMMA)));
		List<PropertyGuaranteeApply> enterpriseEmployments = list(queryWrapper);
		List<PropertyGuaranteeApplyVO> propertyGuaranteeApplyVOS = propertyGuaranteeApplyWrapper.entityToVO(enterpriseEmployments);
		List<PageData> pageDataList = new ArrayList<>();
		try{
			if (CollectionUtil.isNotEmpty(propertyGuaranteeApplyVOS)){
				for (PropertyGuaranteeApplyVO vo : propertyGuaranteeApplyVOS){
					PageData pd = new PageData();
					pd.put("id", vo.getId());
					pd.put("UNITNAME", vo.getApplyName());
					pd.put("APPLICANTNAME", vo.getCreateUserName());
					pd.put("applicantId", vo.getCreateUser());
					pd.put("applyOrganizationId", vo.getApplyNameId());
					pd.put("formType", FormTypeConstant.QG_GUARANTEE_APPLY_FORM);
					pd.put("orgName", vo.getApplyName());
					pageDataList.add(pd);
				}
			}

			return pageDataList;
		} catch (Exception e) {
			log.error(ExceptionUtils.getFullStackTrace(e));
		}
		return pageDataList;
	}

	@Override
	public List<Integer> getFormType() {
		return Arrays.asList(FormTypeConstant.QG_GUARANTEE_APPLY_FORM);
	}

	@Override
	public void goBackToStash(String formId) {
		handleStatus(Long.valueOf(formId), UNREVIEWED,null);
	}

	@Override
	public PageData guaranteeDateAnalysis(PropertyGuaranteeApplyDTO propertyGuaranteeApplyDTO) {
		QueryWrapper<PropertyGuaranteeApply> wrapper = new QueryWrapper<>();
		wrapper.select("guarantee_name", "guarantee_start_date", "guarantee_end_date");
		wrapper.eq("status",3);
		if (Optional.ofNullable(propertyGuaranteeApplyDTO.getApplyNameId()).isPresent()){
			wrapper.in("apply_name_id", orgzationService.getAllChildIds(propertyGuaranteeApplyDTO.getApplyNameId()));
		}

		List<PropertyGuaranteeApply> propertyGuaranteeApplyList = this.list(wrapper);
		ArrayList<String> gnList = new ArrayList<>();
		ArrayList<String> gsdList = new ArrayList<>();
		ArrayList<String> gedList = new ArrayList<>();
		if (CollectionUtil.isNotEmpty(propertyGuaranteeApplyList)) {
			for (PropertyGuaranteeApply propertyGuaranteeApply : propertyGuaranteeApplyList) {
				gnList.add(propertyGuaranteeApply.getGuaranteeName());
				gsdList.add(DateUtil.format(propertyGuaranteeApply.getGuaranteeStartDate(), DateUtil.PATTERN_DATE));
				gedList.add(DateUtil.format(propertyGuaranteeApply.getGuaranteeEndDate(), DateUtil.PATTERN_DATE));
			}
		}
		ArrayList<Object> list = new ArrayList<>();
		HashMap<Object, Object> map1 = new HashMap<>();
		HashMap<Object, Object> map2 = new HashMap<>();
		map1.put("name","结束时间");
		map1.put("data",gedList);
		map2.put("name","开始时间");
		map2.put("data",gsdList);
		list.add(map1);
		list.add(map2);
		PageData pd = new PageData();
		pd.put("axisData",gnList);
		pd.put("series1",list);
		return pd;
	}

	@Override
	public PageData guaranteeAmountTotalAnalysis(PropertyGuaranteeApplyDTO propertyGuaranteeApplyDTO) {
		QueryWrapper<PropertyGuaranteeApply> wrapper = new QueryWrapper<>();
		wrapper.select("guarantee_name", "guarantee_amount", "guarantee_total");
		wrapper.eq("status",3);
		if (Optional.ofNullable(propertyGuaranteeApplyDTO.getApplyNameId()).isPresent()){
			wrapper.in("apply_name_id", orgzationService.getAllChildIds(propertyGuaranteeApplyDTO.getApplyNameId()));
		}
		List<PropertyGuaranteeApply> propertyGuaranteeApplyList =this.list(wrapper);
		ArrayList<String> gnList = new ArrayList<>();
		ArrayList<BigDecimal> AmountList = new ArrayList<>();
		ArrayList<BigDecimal> AmountTotalList = new ArrayList<>();
		if (CollectionUtil.isNotEmpty(propertyGuaranteeApplyList)) {
			for (PropertyGuaranteeApply propertyGuaranteeApply : propertyGuaranteeApplyList) {
				gnList.add(propertyGuaranteeApply.getGuaranteeName());
				AmountList.add(propertyGuaranteeApply.getGuaranteeAmount());
				AmountTotalList.add(propertyGuaranteeApply.getGuaranteeTotal());
			}
		}
		HashMap<Object, Object> map1 = new HashMap<>();
		HashMap<Object, Object> map2 = new HashMap<>();
		map1.put("name","担保金额");
		map1.put("data",AmountList);
		map2.put("name","累计额");
		map2.put("data",AmountTotalList);
		ArrayList<Object> list = new ArrayList<>();
		list.add(map1);
		list.add(map2);
		PageData pd = new PageData();
		pd.put("axisData",gnList);
		pd.put("series2",list);
		return pd;
	}

	/**
	 * 统一处理状态机事件方法
	 *
	 * @param id          主键
	 * @param updateStatus 更新状态
	 * @return boolean
	 */
	private Boolean handleStatus(Long id, int updateStatus,String comment) {
		try {
			PropertyGuaranteeApply propertyGuaranteeApply = getById(id);
			/**
			 * 设置审批人和审批时间
			 */
			if (updateStatus == FormStatusConstant.FINISH){
				propertyGuaranteeApply.setApprovedUser(TokenUtil.getTokenUserId());
				Date now = DateUtil.now();
				propertyGuaranteeApply.setApprovedTime(now);
			}
			if (StringUtil.isNotBlank(propertyGuaranteeApply.getDataSource()) &&
					StringUtil.isNotBlank(propertyGuaranteeApply.getDataSourceId())){
				if (updateStatus == FormStatusConstant.FINISH || updateStatus == FormStatusConstant.REJECT){
					ApprovalMessage approvalMessage = new ApprovalMessage();
					approvalMessage.setDataSourceId(propertyGuaranteeApply.getDataSourceId());
					approvalMessage.setOpinion(comment);
					approvalMessage.setIsApprove(updateStatus == FormStatusConstant.FINISH ? 2 : 1);
					approvalMessage.setIsSend(1);
					approvalMessage.setDataSourceType(GZW_TYPE);
					if (propertyGuaranteeApply.getDataSource().equals(YthConstant.DATA_NINGBO)) {
						approvalMessage.setDataSourceType(YthConstant.DATA_NINGBO);
						approvalMessage.setFilingUserName(UserCache.userIdToName(TokenUtil.getTokenUserId()));
						approvalMessage.setFormType(FormTypeConstant.QG_GUARANTEE_APPLY_FORM);
						approvalMessage.setFilingCode(propertyGuaranteeApply.getCode());
					}
					approvalMessageService.save(approvalMessage);
				}
			}
			propertyGuaranteeApply.setStatus(updateStatus);
			updateById(propertyGuaranteeApply);
			return true;
		} catch (Exception e) {
			log.error(ExceptionUtils.getFullStackTrace(e));
			return false;
		}
	}

	@Override
	public PageData unitRankIdAnalysis(PropertyGuaranteeApplyDTO propertyGuaranteeApplyDTO) {
		List<PropertyGuaranteeApply> propertyGuaranteeApplyList = propertyGuaranteeApplyMapper.unitRankIdAnalysis(propertyGuaranteeApplyDTO);
		ArrayList<Object> dataList = new ArrayList<>();
		PageData pd = new PageData();
		Map<String, String> rankMap = baseInfoService.getChildMap(ValueSetConstant.ENTERPRISE_RANK);
		//排序
		StringBuilder result = new StringBuilder(256);
		Map<String, String> sortedMap = new TreeMap(new Comparator<String>() {
			@Override
            public int compare(String o1, String o2) {
				return o1.compareTo(o2);  //按升序排列 ,改为按降序排列return o2.compareTo(o1);
			}
		});
		sortedMap.putAll(rankMap);
		Map.Entry<String, String> me = null;
		String val = null;
		Iterator it = sortedMap.entrySet().iterator();

		while (it.hasNext()) {
			me = (Map.Entry) it.next();
			val = (String) me.getValue();
			if (val != null) {
				val = val.trim();
				if (!"".equals(val)) {
					result.append(val);
				}
			}
		}
		Collection<String> rankMapValues = sortedMap.values();
		HashMap<String, Object> data1Map = new HashMap<>();
		data1Map.put("legend", rankMapValues);
		Set<String> rankMapKeys = sortedMap.keySet();
		if (CollectionUtil.isNotEmpty(rankMapKeys)) {
			for (String key : rankMapKeys) {
				HashMap<String, Object> nameValueMap = new HashMap<>();
				nameValueMap.put("name", sortedMap.get(key));
				boolean flag = true;
				if (CollectionUtil.isNotEmpty(propertyGuaranteeApplyList)) {
					for (PropertyGuaranteeApply propertyGuaranteeApply : propertyGuaranteeApplyList) {
						if (key.equals(propertyGuaranteeApply.getUnitRankId())) {
							nameValueMap.put("value", propertyGuaranteeApply.getGuaranteeAmount());
							flag = false;
							break;
						}
					}
				}
				if (flag) {
					nameValueMap.put("value", 0);
				}
				dataList.add(nameValueMap);
			}
		}
		data1Map.put("data", dataList);
		pd.put("data1", data1Map);
		return pd;
	}

	@Override
	public PageData guaranteeModeIdAnalysis(PropertyGuaranteeApplyDTO propertyGuaranteeApplyDTO) {
		List<PropertyGuaranteeApply> propertyGuaranteeApplyList = propertyGuaranteeApplyMapper.guaranteeModeIdAnalysis(propertyGuaranteeApplyDTO);
		ArrayList<Object> dataList = new ArrayList<>();
		PageData pd = new PageData();
		Map<String, String> rankMap = baseInfoService.getChildMap(ValueSetConstant.GUARANTEE_MODE);
		//排序
		StringBuilder result = new StringBuilder(256);
		Map<String, String> sortedMap = new TreeMap(new Comparator<String>() {
			@Override
            public int compare(String o1, String o2) {
				return o1.compareTo(o2);  //按升序排列 ,改为按降序排列return o2.compareTo(o1);
			}
		});
		sortedMap.putAll(rankMap);
		Map.Entry<String, String> me = null;
		String val = null;
		Iterator it = sortedMap.entrySet().iterator();
		while (it.hasNext()) {
			me = (Map.Entry) it.next();
			val = (String) me.getValue();
			if (val != null) {
				val = val.trim();
				if (!"".equals(val)) {
					result.append(val);
				}
			}
		}
		Collection<String> rankMapValues = sortedMap.values();
		HashMap<String, Object> data2Map = new HashMap<>();
		data2Map.put("legend", rankMapValues);
		Set<String> rankMapKeys = sortedMap.keySet();
		if (CollectionUtil.isNotEmpty(rankMapKeys)) {
			for (String key : rankMapKeys) {
				HashMap<String, Object> nameValueMap = new HashMap<>();
				nameValueMap.put("name", sortedMap.get(key));
				boolean flag = true;
				if (CollectionUtil.isNotEmpty(propertyGuaranteeApplyList)) {
					for (PropertyGuaranteeApply propertyGuaranteeApply : propertyGuaranteeApplyList) {
						if (key.equals(propertyGuaranteeApply.getGuaranteeModeId())) {
							nameValueMap.put("value", propertyGuaranteeApply.getGuaranteeAmount());
							flag = false;
							break;
						}
					}
				}
				if (flag) {
					nameValueMap.put("value", 0);
				}
				dataList.add(nameValueMap);
			}
		}
		data2Map.put("data", dataList);
		pd.put("data2", data2Map);
		return pd;
	}

	@Override
	public String saveGuaranteeApplyList(String data) {
		YthResult ythResult = new YthResult();
		//成功的id集合
		List<String> successIds = new ArrayList<>();
		//失败的id集合
		List<String> failIds = new ArrayList<>();
		//失败的原因
		List<String> failReasons = new ArrayList<>();
		//将json字符串转换成list
		List<PropertyGuaranteeApply> dataList = JSON.parseArray(data, PropertyGuaranteeApply.class);
		if (CollectionUtil.isNotEmpty(dataList)){
			Map<String, String> orgSource = orgService.getSourceId();

			//根据datasourceIds 查询出所有的数据
			List<PropertyGuaranteeApply> list = list(new LambdaQueryWrapper<PropertyGuaranteeApply>().in(PropertyGuaranteeApply::getDataSourceId, dataList.stream().map(PropertyGuaranteeApply::getDataSourceId).toArray()));
			if (CollectionUtil.isNotEmpty(list)){
				//删除子集
				List<Long> ids = list.stream().map(PropertyGuaranteeApply::getId).collect(Collectors.toList());
				if (CollectionUtil.isNotEmpty(ids)){
					propertyGuaranteeAuditService.deleteLogicByPropertyGuaranteeApplyId(ids);
					propertyGuaranteeWarranteeService.deleteLogicByPropertyGuaranteeApplyId(ids);
				}
			}
			//如果数据库中有数据，就更新，没有就新增
			for (PropertyGuaranteeApply entity:dataList){
				entity.setFormType(String.valueOf(FormTypeConstant.QG_GUARANTEE_APPLY_FORM));
				if (StringUtil.isBlank(entity.getWarranteeCompanyName())){
					failIds.add(entity.getDataSourceId());
					failReasons.add("dataSourceId:"+entity.getDataSourceId()+"被担保人为空，无法保存");
				}else {
					//id重复略过
					transfer(entity,orgSource);
					if (CollectionUtil.isNotEmpty(list)){
						List<String> olIds = list.stream().map(PropertyGuaranteeApply::getDataSourceId).collect(Collectors.toList());
						String dataSourceId = entity.getDataSourceId();
						//判断数据库中是否有数据
						if (olIds.contains(dataSourceId)){
							for (PropertyGuaranteeApply oldEntity:list){
								if (dataSourceId.equals(oldEntity.getDataSourceId())){
									//判断status是否为0，如果是0，就更新，不是0，就不更新
									if (CheckStatus.checkCode(oldEntity.getStatus())){
										successIds.add(dataSourceId);
										entity.setId(oldEntity.getId());
										entity.setDataSource(YthConstant.DATA_NINGBO);
										submit(entity);
										list.remove(oldEntity);
										break;
									}else {
										failIds.add(dataSourceId);
										failReasons.add("dataSourceId:"+dataSourceId+"数据已提交且已经在流程中，无法更新");
										break;
									}
								}
							}
						}else {
							//如果数据库中没有数据，就新增
							entity.setDataSource(YthConstant.DATA_NINGBO);
							submit(entity);
							successIds.add(entity.getDataSourceId());
						}
					}else {
						//如果数据库中没有数据，就新增
						entity.setDataSource(YthConstant.DATA_NINGBO);
						submit(entity);
						successIds.add(entity.getDataSourceId());
					}
				}
			}
		} else {
			failReasons.add("数据为空");
		}
		ythResult.setSuccessIds(successIds);
		ythResult.setFailIds(failIds);
		ythResult.setFailReason(StringUtils.join(failReasons, ";"));
		//ythResult转换成json字符串
		return JSON.toJSONString(ythResult);
	}

	private void transfer(PropertyGuaranteeApply entity, Map<String, String> orgSourceMap){
		Optional.ofNullable(entity.getApplyNameId()).ifPresent(m ->
				{
					String orgId = orgSourceMap.get(m);
					entity.setApplyNameId(orgId);
					entity.setCreateCompanyId(orgId);
				}
		);

		Optional.ofNullable(entity.getGuaranteeCompanyId()).ifPresent(m ->
				{
					String orgId = orgSourceMap.get(m);
					entity.setGuaranteeCompanyId(orgId);
				}
		);

	}

}
